(async function() {

  let spinesData = {
    indexSpineList: [],
    popupSpineList: []
  }
  let defaultIndexSpine
  let testGetSpinesJson = chrome.runtime.getURL('../config/spinesData.json')
  var xhr = new XMLHttpRequest()
  xhr.open("GET", testGetSpinesJson, true) 
  xhr.send()
  const getSpinesData = () => {
    return new Promise((resolve,reject) => {
      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4 && xhr.status === 200) {
          resolve(xhr.responseText)
        }
      }
    })
  }
  const getStorageSpinesData = () => {
    return new Promise((resolve, reject) => {
      chrome.storage.sync.get('IndexSpine', storageRes => {
        resolve(storageRes.IndexSpine)
      });
    })
  }
  const getStorageSpineDirection = () => {
    return new Promise((resolve, reject) => {
      chrome.storage.sync.get('spineDirection', storageRes => {
        resolve(storageRes.spineDirection)
      });
    })
  }
  const getStorageScaleMult = () => {
    return new Promise((resolve, reject) => {
      chrome.storage.sync.get('scaleMult', storageRes => {
        resolve(storageRes.scaleMult)
      });
    })
  }
  window.addEventListener('settingPositionEvent', () => {
    let selectSpine = spinesData.popupSpineList.find(p => p.key === settingOption.key)
    settingOption.skelPath = selectSpine?.skelPath
    settingOption.atlasPath = selectSpine?.atlasPath
    spinesData.indexSpineList = [settingOption]
    chrome.storage.sync.set({'IndexSpine': JSON.stringify(spinesData)}, function() {
    });
    settingOption = null
  });
  // let popupSpineList=  []
  let globalSpine
  let spineDirection
  let scaleMult
  await getSpinesData().then(async (res) => {
    defaultIndexSpine = JSON.parse(res).indexSpineList[0]
    spinesData = JSON.parse(res)
    // popupSpineList = spinesData.popupSpineList
    await getStorageSpinesData().then(storageRes => {
      if (storageRes) {
        storageRes = JSON.parse(storageRes)
        globalSpine = storageRes.indexSpineList[0]
      }
      else {
        globalSpine = spinesData.indexSpineList[0]
      }
      // globalSpine = spinesData.indexSpineList[0]
    })
    await getStorageSpineDirection().then(storageRes => {
      spineDirection = storageRes||-1
    })
    await getStorageScaleMult().then(storageRes => {
      scaleMult = storageRes||0.3
    })
  })
  .catch(err => {
    console.log(err)
  })


  // XMLHttpRequest方案
  // let xhrCharload = new XMLHttpRequest()
  // let spinesFilesPath = chrome.runtime.getURL('../spine')
  // xhrCharload.open("GET", spinesFilesPath, true)
  // xhrCharload.send()
  // const getFiles = () => {
  //   return new Promise((resolve, reject) => {
  //     xhrCharload.onreadystatechange = function () {
  //       if (xhrCharload.readyState === 4 && xhrCharload.status === 200) {
  //         resolve(xhrCharload.responseText)
  //       }
  //     }
  //   })
  // }
  // let charloadData
  // await getFiles().then(res => {
  //   charloadData = res
  // })

  // ActiveXObject方案
  // var fso = new ActiveXObject("Scripting.FileSystemObject");
  // // 获取文件相关信息
  // var drv;
  // // 获取磁盘相关信息
  // drv = fso.GetDrive(fso.GetDriveName("../spine"));
  // console.log(drv)

  Ospine.injectOption({
    spineList: JSON.parse(JSON.stringify([globalSpine])),
    scaleXGlobal: spineDirection,
    scaleMult: scaleMult
  })
  Ospine.init()
  // chrome.storage.onChanged.addListener(function(changes, namespace) {
  //   for (key in changes) {
  //     var storageChange = changes[key];
  //     console.log('Storage key "%s" in namespace "%s" changed. ' +
  //                 'Old value was "%s", new value is "%s".',
  //                 key,
  //                 namespace,
  //                 storageChange.oldValue,
  //                 storageChange.newValue);
  //   }
  // });
  
  
  chrome.runtime.onMessage.addListener(
    async (request, sender, sendResponse) => {
     
      if (!request.action) {
        sendResponse({code: 10000, msg: '无效的请求'});
        return
      }
      const spineState = window.getComputedStyle(o_canvas_spine, 'display').display;
      const positionLineState = window.getComputedStyle(o_spine_position).borderStyle
      switch (request.action) {
        case 'changeSpineState':
          o_canvas_spine.style.display = spineState == 'block' ? 'none' : 'block'
          sendResponse({code: 200, msg: 'success'});
          break;
        case 'getSpineState':
          if (spineState === 'block') {
            sendResponse({code: 200, msg: 'success', data: {
              state: spineState, 
              spine: globalSpine.key, 
              positionState: positionLineState,
              direction: spineDirection,
              scale: scaleMult
            }});
          }
          else {
            sendResponse({code: 200, msg: 'success', data: {
              state: spineState, 
              spine: null, 
              positionState: 'none',
              direction: 0,
              scale: 0.1
            }});
          }
          break;
        case 'selectSpine':
          if (!request.spine) {
            sendResponse({code: 10001, msg: '没有可用的人物'});
            break;
          }
          let selectSpine = spinesData.popupSpineList.find(p => p.key === request.spine)
          globalSpine = JSON.parse(JSON.stringify(selectSpine))
          if (!globalSpine) {
            sendResponse({code: 10002, msg: '没有找到人物'});
            break;
          }
          globalSpine.isIndex = true
          Ospine.destroy()
          Ospine.injectOption({spineList: JSON.parse(JSON.stringify([globalSpine]))})
          Ospine.init()
          spinesData.indexSpineList = [globalSpine]
          chrome.storage.sync.set({'IndexSpine': JSON.stringify(spinesData)}, function() {
          });
          sendResponse({code: 200, msg: 'success'});
          break;
        case 'getPositionLineState':
          sendResponse({code: 200, msg: 'success', data: {state: positionLineState}});
          break
        case 'changePositionLine':
          o_spine_position.style.border = positionLineState == 'none' ? '1px solid red' : 'none'
          sendResponse({code: 200, msg: 'success'});
          break
        case 'changeDirection':
          const direction = request.direction?1:-1
          Ospine.changeDirection(direction)
          chrome.storage.sync.set({'spineDirection': direction}, () => {
          });
          sendResponse({code: 200, msg: 'success'});
          break
        case 'settingPosition':
          osp_position_setting.style.display = 'flex'
          Ospine.settingPosition(true)
          sendResponse({code: 200, msg: 'success'});
          break
        case 'changeScale':
          Ospine.changeScale(request.value/100)
          sendResponse({code: 200, msg: 'success'});
          break
        case 'submitScale':
          scaleMult = request.value/100
          chrome.storage.sync.set({'scaleMult': request.value/100}, () => {
          });
          sendResponse({code: 200, msg: 'success'});
          break
        case 'loadchar':
          console.log('2222')
          sendResponse({code: 200, msg: 'success'});
          break
        case 'defaultSetting':
          chrome.storage.sync.clear()
          Ospine.destroy()
          globalSpine = defaultIndexSpine
          scaleXGlobal = -1
          scaleMult = 0.3
          Ospine.injectOption({
            spineList: JSON.parse(JSON.stringify([globalSpine])),
            scaleXGlobal: scaleXGlobal,
            scaleMult: scaleMult
          })
          Ospine.init()
          sendResponse({code: 200, msg: 'success'});
          break
        default:
          break;
     }
   }
  );
  opsSettingSubmit.onclick = () =>{
    let selectSpine = spinesData.popupSpineList.find(p => p.key === settingOption.key)
    settingOption.skelPath = selectSpine?.skelPath
    settingOption.atlasPath = selectSpine?.atlasPath
    spinesData.indexSpineList = [settingOption]
    chrome.storage.sync.set({'IndexSpine': JSON.stringify(spinesData)}, function() {
    });
    settingOption = null
    osp_position_setting.style.display = 'none'
    Ospine.settingPosition(false)
    o_spine_position.style.border = 'none'
  }
  opsSetingCancel.onclick = () => {
    settingOption = null
    osp_position_setting.style.display = 'none'
    Ospine.settingPosition(false)
    o_spine_position.style.border = 'none'
  }
})()
